# -*- coding: utf-8 -*-

from django.db import models
from django.contrib.auth.models import User

#from cprt.accounts.models import UserDetail


class Dept(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=45)
    superior_dept=models.ForeignKey('self',null=True)
    principal_auth_user=models.ForeignKey(User)
       
    class Meta:
        db_table="DEPT"
        
    def __unicode__(self):
        return self.name
    
class Holiday(models.Model):
    id = models.AutoField(primary_key=True)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()
    memo = models.CharField(max_length=30)
    
    class Meta:
        db_table = "HOLIDAY"
    
    def __unicode__(self):
        return "Holiday:%s" % self.memo
    
class Workday(models.Model):
    id = models.AutoField(primary_key=True)
    at_date = models.DateField()
    memo = models.CharField(max_length=30)
    
    class Meta:
        db_table = 'WORKDAY'
    
    def __unicode__(self):
        return 'Workday:%s' % self.memo
        
    
    
#def get_my_dept_by_user(user):
#    try:
#        return Dept.objects.get(principal_auth_user=user)
#    except Dept.DoesNotExist:
#        return None

#def get_my_dept(user_id):
#    try:
#        return Dept.objects.get(principal_auth_user=User.objects.get(pk=user_id))
#    except Dept.DoesNotExist:
#        return None

def get_my_depts(user):
    return Dept.objects.filter(principal_auth_user=user)

def get_my_branchs2(user):
    my_dept_qs = get_my_depts(user)
    dept_list = []
    for dept in my_dept_qs:
        get_branchs(dept_list, dept)
    return dept_list

#def get_my_branchs(user_id):
#    dept = get_my_dept(user_id)
#    if dept == None:
#        return []
#    dept_list=[]
#    get_branchs(dept_list,dept)
#    return dept_list
            
def get_branchs(list, dept):
    qs = Dept.objects.filter(superior_dept=dept)
    for d in qs:
        list.append(d)
        get_branchs(list,d)
